package cn.kgc.layui.servlet;

import cn.kgc.layui.dao.ManagerDao;
import cn.kgc.layui.dao.impl.ManagerDaoImpl;
import cn.kgc.layui.entity.Authority;
import cn.kgc.layui.entity.Manager;
import cn.kgc.layui.util.LayUiResult;
import cn.kgc.layui.vo.LoginVO;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/login/*")
public class LoginServlet extends BaseServlet<LoginVO> {
    ManagerDao managerDao=new ManagerDaoImpl();

    public void loginUI(HttpServletRequest req, HttpServletResponse resp,LoginVO loginVO) throws ServletException, IOException {
        req.getRequestDispatcher("/login.jsp").forward(req,resp);
    }

    public void doLogin(HttpServletRequest req, HttpServletResponse resp,LoginVO loginVO) throws IOException {
        Manager manager= managerDao.doLogin(loginVO);
        LayUiResult result;
        if(null!=manager){
            //登录成功
            //用户信息存入session
            req.getSession().setAttribute("manager",manager);
            //查询用户所拥有的所有权限菜单
            List<Authority> authorityList= managerDao.getAuth(manager.getId()+"");
            req.getSession().setAttribute("authorityList",authorityList);
            result=LayUiResult.builder().code(0).msg("登录成功").build();

        }else{
            //登录失败
            result=LayUiResult.builder().code(500).msg("用户名或者密码错误").build();
        }
        String strResult = JSON.toJSONString(result);
        resp.getWriter().write(strResult);
    }

    public void quit(HttpServletRequest req, HttpServletResponse resp,LoginVO loginVO) throws IOException {
        req.getSession().invalidate();
        resp.sendRedirect("/login/loginUI");

    }



}
